package com.cardone.persistent.support;

import com.cardone.context.ContextHolder;
import com.google.common.collect.Maps;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2014/11/11.
 */
public class TreeRedundancyUpdateAction extends RedundancyUpdateAction {
    @Setter
    protected Integer level = 9;

    public TreeRedundancyUpdateAction() {
        this.findSqlId = "/platform/findTreeRedundancyByCode";
        this.updateSqlId = "/platform/updateTreeRedundancyByCode";
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void run() {
        this.run(null, this.level);

        if (CollectionUtils.isEmpty(this.children)) {
            return;
        }

        for (RedundancyUpdateAction redundancyUpdateAction : this.children) {
            redundancyUpdateAction.run();
        }
    }

    public void run(Map<String, Object> parentUpdateMap, Integer level) {
        if (level < 1) {
            return;
        }

        JdbcTemplateSupport jdbcTemplateSupport = ContextHolder.getBean(JdbcTemplateSupport.class);

        Map<String, Object> newModel = Maps.newHashMap(this.model);

        if (MapUtils.isNotEmpty(parentUpdateMap)) {
            newModel.putAll(parentUpdateMap);
        }

        List<Map<String, Object>> updateMapList = jdbcTemplateSupport.findList(this.findSqlId, newModel);

        if (CollectionUtils.isEmpty(updateMapList)) {
            return;
        }

        jdbcTemplateSupport.batchUpdate(this.updateSqlId, newModel, updateMapList);

        for (Map<String, Object> updateMap : updateMapList) {
            Map<String, Object> newParentUpdateMap = Maps.newHashMap(newModel);

            newParentUpdateMap.putAll(updateMap);

            this.run(newParentUpdateMap, (level - 1));
        }
    }
}
